<?php
class PeerModel extends BaseModel
{
    private $peer_db;
    public function __construct()
    {
        parent::__construct();
        $this->peer_db = new PeerDb();
    }

    public function getPeers($info_hash, $no_peer_id = true, $delete_peer_ids=array())
    {
        $where = array(
            'e' => array(
                'info_hash' => $info_hash,
                'event' => array(PeerDb::$event['started'], PeerDb::$event['completed']),
            ),
        );
        $r = $this->peer_db->selectRows($where);
        $data = array(
            'peers' => array(),
            'complete' => 0, //todo
            'incomplete' => 0, //todo
        );
        foreach($r as $one) {
            $tmp = array();
            if(in_array($one['id'], $delete_peer_ids)) {
                continue;
            }
            $tmp = array();
            if(!$no_peer_id) {
                $tmp['peer id'] = $one['id'];
            }
            $tmp['ip'] = $one['ip'];
            $tmp['port'] = intval($one['port']);
            switch($one['event']) {
                case PeerDb::$event['completed'] :
                    $data['complete'] += 1;
                    break;
                case PeerDb::$event['started'] :
                    if($one['left'] == 0) {
                        $data['complete'] += 1;
                    } else {
                        $data['incomplete'] += 1;
                    }
                    break;
            }
            $data['peers'][] = $tmp;
        }
        return $data;
    }

    public function set($data)
    {
        //todo 一个用户下一个种子，peer_id必须只有一个，不能覆盖，比如开2个软件刷分，轮流请求peers，轮流覆盖。
        //当收到stoped请求时删除记录，然后可以用另一个软件下载。当用户硬盘损坏时死机，无法收到stoped请求，换OS后重装bt软件，peer_id就变了，无法再下载了？方案：每个started都记录时间，如果一个started很久没有更新，说明非正常关机了，可以清理了，也防止别的用户总收到这个失效ip。
        //检查torrent是否属于本站
        $where = array(
            'e' => array(
                'info_hash' => $data['info_hash'],
            ),
        );
        $torrent_db = new TorrentDb();
        $t = $torrent_db->selectRow($where);
        error_log(var_export($t, true));
        if(empty($t)) {
            throw new ModelException();
        }
        //todo 以后如果有游戏，那应该在torrent表中添加category表明是电影还是游戏
        $movie_uri_db = new MovieUriDb();
        $where = array(
            'e' => array(
                'torrent_id' => $t['id'],
            ),
        );
        $r = $movie_uri_db->selectRow($where, array('rating'));
        error_log(var_export($r, true));
        $rating = $r['rating'];
        if($rating >= 9) {
            $upload_multiple = 2; //上传倍率是2
            $download_multiple = 0; //下载倍率是0
        } elseif($rating >=8) {
            $upload_multiple = 1;
            $download_multiple = 0;
        } elseif($rating >=7) {
            $upload_multiple = 1;
            $download_multiple = 0.5;
        } else {
            $upload_multiple = 1;
            $download_multiple = 1;
        }

        error_log('upload_multiple' . $upload_multiple .', download_multiple'.  $download_multiple);
        $where = array(
            'e' => array(
                'user_id' => $data['user_id'],
                'info_hash' => $data['info_hash'],
            ),
        );
        if(isset($data['event'])&&!empty($data['event'])) {
            $data['event'] = PeerDb::$event[$data['event']];
            if($data['event'] == PeerDb::$event['stopped']) {
                $this->peer_db->delete($where);
            }
        }
        $peer = $this->peer_db->selectRow($where);
        $data['update_time'] = time();
        if(empty($peer)) {
            $r = $this->peer_db->insertRow($data);
        } else {
            //计算上次请求到现在的 上传下载量，增加到用户数据中。
            $uploaded = $data['uploaded'] - $peer['uploaded'];
            $downloaded = $data['downloaded'] - $peer['downloaded'];
            $traffice = array(
                'uploaded' => $uploaded > 0 ? ceil($uploaded * $upload_multiple) : 0, //如果之前未清理，会出现负的
                'downloaded' => $downloaded > 0 ? floor($downloaded * $download_multiple) : 0,
            );
            $user_model = new UserModel();
            $user_model->updateTraffic($data['user_id'], $traffice);
            $r = $this->peer_db->update($data, $where);
        }
        return $r;
    }

    public function update($data)
    {
        $where = array(
            'e' => array(
                'user_id' => $data['user_id'],
                'info_hash' => $data['info_hash'],
            ),
        );
        $this->movie_db->select($data, $where);
        return $id;
    }
}
?>
